public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        int len = nums.length;
        for(int i = 0; i < len; i++) {
            if(!set.contains(nums[i])) {
                set.add(nums[i]);
            } else {
                if(i - getLastIndex(nums, nums[i], i) <= k) {
                    return true;
                }
            }
        }
        return false;
    }

    private int getLastIndex(int[] nums, int num, int index) {
        for(int i = index - 1; i >= 0; i--) {
            if(num == nums[i]) {
                return i;
            }
        }
        return Integer.MIN_VALUE;
    }
}